/*
 *  Copyright 2005 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.forum.post;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.ForumModuleConstants;
import com.blandware.atleap.common.util.HtmlUtil;
import com.blandware.atleap.common.util.StringUtil;
import com.blandware.atleap.model.core.Role;
import com.blandware.atleap.model.core.User;
import com.blandware.atleap.model.forum.Post;
import com.blandware.atleap.model.forum.Topic;
import com.blandware.atleap.search.SearchManager;
import com.blandware.atleap.service.core.UserManager;
import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
import com.blandware.atleap.service.exception.OwnerNotFoundException;
import com.blandware.atleap.service.forum.ForumManager;
import com.blandware.atleap.service.util.MailEngine;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.forum.PostForm;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import com.blandware.atleap.webapp.util.forum.ForumModuleWebConstants;
import com.blandware.atleap.webapp.util.forum.ForumModuleWebUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>Creates a post.</p>
 * <p><a href="CreatePostAction.java.html"><i>View source</i></a></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.6 $ $Date: 2008/04/29 17:51:51 $
 * @struts.action path="/forum/post/create"
 * name="postForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * @struts.action-forward name="inputForward"
 * path=".forum.post.create"
 * @struts.action-forward name="showForum"
 * path="/forum/forum/show.do"
 * redirect="true"
 * @struts.action-forward name="showTopic"
 * path="/forum/topic/show.do"
 * redirect="true"
 * @struts.action-forward name="deleteSubscription"
 * path="/forum/subscription/delete.do"
 * redirect="true"
 * @struts.action-forward name="unsatisfiable"
 * path="/forum/forum/show.do"
 */
public final class CreatePostAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		if ( !isCancelled(request) ) {

            PostForm postForm = (PostForm) form;
            String preparedBody = StringUtil.asSingleLine(StringUtil.escapeDoubleQuotesForJs(HtmlUtil.cutOffHtmlAsForumPost(postForm.getBody())));
            request.setAttribute("preparedBody", preparedBody);

            request.setAttribute("previewing", Boolean.FALSE);
            request.setAttribute("fullName", null);
            if (request.getParameter("preview") != null) {
                // just previewing
                String remoteUser = request.getRemoteUser();
                boolean anonymous = remoteUser == null;
                if (!anonymous) {
                    UserManager userManager = (UserManager) getBean(Constants.USER_MANAGER_BEAN);
                    User user = userManager.retrieveUser(remoteUser);
                    String fullName = null;
                    if (user != null) {
                        fullName = user.getFullName();
                    }
                    request.setAttribute("fullName", fullName);
                }
                postForm.setBody(HtmlUtil.cutOffHtmlAsForumPost(postForm.getBody()));

                request.setAttribute("previewing", Boolean.TRUE);
                saveToken(request);
                return mapping.getInputForward();
            }

            Post post = new Post();
            WebappUtil.copyProperties(post, postForm, request);

            HttpSession session = request.getSession();

            Long topicId;
            topicId = (Long) session.getAttribute(ForumModuleWebConstants.TOPIC_ID_KEY);

            if (topicId == null) {
				// no topic ID
                if (log.isDebugEnabled()) {
                    log.debug("No topic ID was found while tried to create a post; going back to forums");
                }
				return mapping.findForward("showForum");
            }

			ForumManager forumManager = (ForumManager) getBean(ForumModuleConstants.FORUM_MANAGER_BEAN);
            Topic topic = forumManager.retrieveTopic(topicId);
            if (topic == null) {
                // no topic found
                ActionMessages errors = new ActionMessages();
                errors.add("ownerNotFound", new ActionMessage("forum.post.errors.ownerNotFound"));
                saveErrors(request, errors);
                return mapping.findForward("showForum");
            }

            String remoteUser = request.getRemoteUser();
            boolean anonymous = remoteUser == null;
            UserManager userManager = (UserManager) getBean(Constants.USER_MANAGER_BEAN);
            User user = null;
            if (!anonymous) {
                user = userManager.retrieveUser(remoteUser);
                if (user == null) {
                    // no user found
                    ActionMessages errors = new ActionMessages();
                    errors.add("userNotFound", new ActionMessage("forum.post.errors.userNotFound"));
                    saveErrors(request, errors);
                    return mapping.findForward("showForum");
                }
            }

            if (anonymous) {
                // author name should be entered
                if (GenericValidator.isBlankOrNull(postForm.getAuthorStr())) {
                    ActionMessages errors = new ActionMessages();
                    errors.add("incorrectAuthorStr", new ActionMessage("forum.post.errors.incorrectAuthor"));
                    saveErrors(request, errors);
                    saveToken(request);
                    return mapping.getInputForward();
                }
            }

            Map titleMap = new HashMap();
            titleMap.put(topic.getForum().getLanguage().getIdentifier(), postForm.getSubject());
            post.setTitle(titleMap);
            post.setAuthorUser(user);
            post.setAuthorStr(post.getAuthor());
            post.setEmailStr(post.getEmail());

            post.setFirst(Boolean.FALSE);
            post.setBody(HtmlUtil.cutOffHtmlAsForumPost(postForm.getBody()));

			try {
				Long postId = forumManager.createPost(post, topicId);

			    String uri = ForumModuleWebConstants.FORUM_URI_PREFIX + "/post" + postId;
			    post.setUri(uri);

                // Assigning same roles as forum has
                List forumRoles = new ArrayList(topic.getForum().getRoles());
                for (Iterator i = forumRoles.iterator(); i.hasNext(); ) {
                    Role role = (Role) i.next();
                    post.addRole(role);
                }

			    forumManager.updatePost(post, topicId);

                if ( post.getActive().booleanValue() ) {
                    // index post
                    SearchManager searchManager = SearchManager.getInstance(request.getSession().getServletContext());
                    searchManager.reIndexPage(post, request);
                }

                MailEngine mailEngine = (MailEngine) getBean(Constants.MAIL_ENGINE_BEAN);
                ForumModuleWebUtil.sendTrackMessages(post, forumManager,
                        mailEngine, mapping.findForward("deleteSubscription"),
                        request, response);
			} catch (OwnerNotFoundException e) {
				ActionMessages errors = new ActionMessages();
				errors.add("ownerNotFound", new ActionMessage("forum.post.errors.ownerNotFound"));
				saveErrors(request, errors);
				saveToken(request);
				return mapping.findForward("showTopic");
            } catch ( BeanAlreadyExistsException e ) {
				// topic already exists
				ActionMessages errors = new ActionMessages();
				errors.add("postAlreadyExists", new ActionMessage("forum.post.errors.alreadyExists"));
				saveErrors(request, errors);
				saveToken(request);
				return mapping.getInputForward();
			}
        }

        return mapping.findForward("showTopic");
	}
}
